package api;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadPoolExecutorTests {


    //创建任务队列,存储待执行的任务
        static  BlockingQueue<Runnable> workQueue =
                new ArrayBlockingQueue<>(1);

    //构建线程工厂
    static ThreadFactory threadFactory = new ThreadFactory() {
        //线程名前缀
        private String prefix = "pool-thread-task-";
        //定义一个提供自增自减机制的对象
        private AtomicLong atomicLong = new AtomicLong(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r,prefix+atomicLong.getAndIncrement());
        }
    };


    public static void main(String[] args) {
        //初始化一个线程池
        ThreadPoolExecutor tpool =
                new ThreadPoolExecutor(1,
                        2,
                        3,
                        TimeUnit.SECONDS,
                        workQueue,
                        threadFactory,
                        //ThreadPoolExecutor.CallerRunsPolicy()调用者执行
                        //主线程放弃执行!!!
                        new ThreadPoolExecutor.CallerRunsPolicy());



        tpool.execute(new Runnable() {
            @Override
            public void run() {

                String task = Thread.currentThread().getName()+"->task01";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        tpool.execute(new Runnable() {
            @Override
            public void run() {
                String task = Thread.currentThread().getName()+"->task02";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        tpool.execute(new Runnable() {
            @Override
            public void run() {
                String task = Thread.currentThread().getName()+"->task03";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        tpool.execute(new Runnable() {
            @Override
            public void run() {
                String task = Thread.currentThread().getName()+"->task04";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
